function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name + '</a> ' +
                      'Phone: (' + json.tmpo_poc_phone.substr(0,3) + ') ' +
                      json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    ); 
}


var attrs_1970 = {};
var actions = {};
var destinations = {};
var dates_url = '/api/dates/';
var drivers_url = '/api/tmpo/drivers/';
var action_url = '/api/tmpo/vehicles/action/';
var history_url = '/api/tmpo/vehicles/history/';
var history_action_url = '/api/tmpo/vehicles/history/action/';
var destination_url = '/api/tmpo/vehicles/history/destination/';
var used_date = '';
var display_date = '';
var vehicle_id = '';
var drivers = [];
var vehicle_no = '';

var loadDrivers = function() {
    $.ajax({
        type:'GET',
        url:drivers_url,
        dataType:'json',
        async:false,
        success:function(response) {
            drivers = response['drivers'];
        }
   })
}


var readDate = function() {
    var today = '';
    var qsdate = getQueryStringVariable('date');
    $.ajax({
        url:(qsdate) ? (dates_url+qsdate+'/') : dates_url,
        type:'GET',
        dataType:'json',
        async:false,
        success:function(json) {
            today = json.info[0].today;
            display_date = json.info[0].display;
        }
    })
    return today
}


var loadVehicleHistory = function() {
    used_date = readDate();
    $.ajax({
        url:history_url + vehicle_id + '/' + used_date + '/',
        type:'GET',
        dataType:'json',
        async:false,
        success:function(json) {
            attrs_1970 = json;
            actions = json.actions;
            destinations = json.destinations;
            loadVehicle();
        },
        error:function(req, status, error){    
            makeNewForm();
      }
   })
}
var makeNewForm = function() {

    var makeForm = {}; 
    makeForm.vehicle_id = getQueryStringVariable('id');
    makeForm.dd1970_date = used_date;
    makeForm.registration_number = testNone("");
    makeForm.administration_number = testNone("");
    makeForm.organization_name = '';
    makeForm.departure_location = '';
    makeForm.departure_time = testNone("");
    makeForm.fuel = testNone("");
    makeForm.oil = testNone("");
    makeForm.passengers = testNone("");
    makeForm.trip = testNone("");
    makeForm.tons_of_cargo = '';
    makeForm.standby_status = '';
  
    $.ajax({
      type:'PUT',
      url:'/api/tmpo/vehicles/history/',
      dataType:'json',
      data :makeForm,
      async:false,
      complete:function() {
        //console.debug('Put complete');
        loadVehicleHistory();
         }
      });

}
var loadVehicle = function() {
    $.ajax({
        type:'GET',
        url:'/api/tmpo/vehicles/' + getQueryStringVariable('id') + '/',
        dataType:'json',
        async:false,
        success:function(json) {
            vehicle_no = json.vehicles[0].vehicleno;
        }
   })
}


var valOf = function(selector) {
    return $(selector).val()
}

function deleteAction(row) {
    var deleteCommitment = function(){
        $.ajax({
            type: "DELETE",
            url:  history_action_url + row.vha_id+'/',
            dataType: "text",
            success: function(){
            resetForm();
            }
        });
        clearTimeout(timeout_index);
        delete timeout_index;
    }
    timeout_index = setTimeout(deleteCommitment, 10000);
    $(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){ 
            deleteCommitment();
        }
    });
    $("#action_edit > tr").remove();
    $("#action_edit").append('<tr><td colspan="10"><b>This vehicle has been deleted. <span id="close_delete_' + row.vha_id + '" class="inferLink"><u>Close</u></span> | <span id="undo_delete_' + row.vha_id + '" class="inferLink"><u>Undo</u></span></b></td></tr>');
    doBinds();
    $("#close_delete_" + row.vha_id).click(function () {
        deleteCommitment(); 
        resetForm();
    });
    $("#undo_delete_" + row.vha_id).click(function () {
        clearTimeout(timeout_index); 
        delete timeout_index;
        resetForm();
  
    });
}


var updateAction = function(action_id) {
    var actionDetails = {};
        actionDetails.checkin_miles = valOf('#checkin_miles');
        actionDetails.checkout_miles = valOf('#checkout_miles');
        actionDetails.checkin_time = valOf('#checkin_time');
        actionDetails.checkout_time = valOf('#checkout_time');
        actionDetails.poc_name = valOf('#poc_name');
        actionDetails.driver_id = valOf('#driver_id');
        actionDetails.vha_id = action_id;

    $.ajax({
        url:history_action_url + action_id + '/',
        type:'POST',
        data:actionDetails,
        success:function() {
            //console.debug('updated action ok');
            resetForm();
        },
        error:function() {
            //console.debug('updated action fail');
        }
    });
}



function deleteDest(row) {
    var deleteCommitment = function(){
        $.ajax({
            type: "DELETE",
            url:  destination_url + row.vhd_id+'/',
            dataType: "text",
            success: function(){
            resetForm();
            }
        });
        clearTimeout(timeout_index);
        delete timeout_index;
    }
    timeout_index = setTimeout(deleteCommitment, 10000);
    $(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){ 
            deleteCommitment();
        }
    });
    $("#destination_edit > tr").remove();
    $("#destination_edit").append('<tr><td colspan="10"><b>This vehicle has been deleted. <span id="close_delete_' + row.vhd_id + '" class="inferLink"><u>Close</u></span> | <span id="undo_delete_' + row.vhd_id + '" class="inferLink"><u>Undo</u></span></b></td></tr>');
    doBinds();
    $("#close_delete_" + row.vhd_id).click(function () {
        deleteCommitment(); 
        resetForm();
    });
    $("#undo_delete_" + row.vhd_id).click(function () {
        clearTimeout(timeout_index); 
        delete timeout_index;
        resetForm();
  
    });
}

var updateDest = function(vhd_id) {
    var destinationDetails = {};
        destinationDetails.comments = valOf('#comments_new');
        destinationDetails.departure_time = valOf('#departure_time_new');
        destinationDetails.arrival_time = valOf('#arrival_time_new');
        destinationDetails.destination = valOf('#destination_new');
        destinationDetails.vhd_id = vhd_id;

    $.ajax({
        url:destination_url + vhd_id + '/',
        type:'POST',
        data:destinationDetails,
        success:function() {
            //console.debug('updated destination ok');
            resetForm();
        },
        error:function() {
            //console.debug('updated destination fail');
        }
    });
}


// TODO:  validate and account for unsaved action(s)/destination(s)
var onSave = function() {
    $('#message').remove();
    $("td[class='tableErrorColor']").removeClass('tableErrorColor');
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("select[class='formError']").removeClass('formError');
    form1970Details = {};
        form1970Details.vehicle_id = vehicle_id;
        form1970Details.dd1970_date = verifyMilitaryDate($("#date").text());
        form1970Details.registration_number = valOf("#registration");
        form1970Details.administration_number = valOf('#admin');
        form1970Details.organization_name = valOf('#org');
        form1970Details.departure_location = valOf('#from');
        form1970Details.departure_time = valOf('#depart');
        form1970Details.fuel = valOf('#fuel');
        form1970Details.oil = valOf('#oil');
        form1970Details.passengers = testNone(valOf('#passengers'));
        form1970Details.trip = testNone(valOf('#trip'));
        form1970Details.tons_of_cargo = valOf('#tons_of_cargo');
        form1970Details.standby_status = valOf('#standby_status');

    var url = (attrs_1970.vh_id) ? (history_url + attrs_1970.vh_id + "/") : history_url;
    var meth = (attrs_1970.vh_id) ? 'POST' : 'PUT';
    //console.log(url, meth)
    //console.log(form1970Details);

    $.ajax({
        url:url,
        type:meth,
        data:form1970Details,
        success:function () {
            $("#button_cancel :last").text("Close");
            $("#button_save").parent().append('<span class="errorMessage">Saved</span>');
            resetForm();
        },
        error:function () {
            //console.log(arguments);
        }
    });
}
function testNone(value) {
  if (value == "") 
  {
    value = '0';
  }
  else
  {
    
  }

return value;
}


function validateAction(btnAfter) {
    var error_count = 0;
    $('#message').remove();
    $("td[class='tableErrorColor']").removeClass('tableErrorColor');
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("select[class='formError']").removeClass('formError');

    if( !verifyMilitaryTime($('#checkin_time').val())) {
        error = 'Please use four-digit military time. Example: 1430 ';
        error_count++;
        $('#checkin_time').parent().append('<span class="errorMessage">'+error+'</span>');
        $('#checkin_time').parent().addClass('tableErrorColor');
        $('#checkin_time').addClass('formError');
    } else {
        var checkin_time = verifyMilitaryTime($('#checkin_time').val());
    }
    
    if( !verifyMilitaryTime($('#checkout_time').val())) {
        error = 'Please use four-digit military time. Example: 1430 ';
        error_count++;
        $('#checkout_time').parent().append('<span class="errorMessage">'+error+'</span>');
        $('#checkout_time').parent().addClass('tableErrorColor');
        $('#checkout_time').addClass('formError');
    } else {
        var checkout_time = verifyMilitaryTime($('#checkout_time').val());
    }

    if (checkin_time < checkout_time) {
        error = "Checkin time must be after checkout time.";
        error_count++;
        $("#checkin_time").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#checkin_time").parent().addClass("tableErrorColor");
        $("#checkin_time").addClass("formError");
        $("#checkout_time").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#checkout_time").parent().addClass("tableErrorColor");
        $("#checkout_time").addClass("formError");
    }

    if ($("#checkout_miles").val() > $("#checkin_miles").val()) {
        error = "Finish date must be on or after start date.";
        error_count++;
        $("#checkout_miles").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#checkout_miles").parent().addClass("tableErrorColor");
        $("#checkout_miles").addClass("formError");
        $("#checkin_miles").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#checkin_miles").parent().addClass("tableErrorColor");
        $("#checkin_miles").addClass("formError");
    }
    var reqFieldList = ['driver_id'];

    jQuery.map(reqFieldList, function(field) { 
    if( !$("#"+field).val()) {
        error = "Please complete required field.";
        error_count++;
        $("#"+field).parent().append('<br /><span class="errorMessage">'+error+'</span>');
        $("#"+field).parent().addClass("tableErrorColor");
        $("#"+field).addClass("formError");
        }
    });

    if (error_count) {
        $("#" + btnAfter).after('<span class="generalErrorMessage" name="message" id="message"><img alt="" src="/tmpo/images/icons/alert.gif"/>Please correct errors above to save action data.</span>')
    } else {
        return true;
    }
}

function validateDest(btnAfter) {
    var error_count = 0;
    $("#message").remove();
    $("td[class='tableErrorColor']").removeClass("tableErrorColor");
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("select[class='formError']").removeClass('formError');

    if( !verifyMilitaryTime($("#arrival_time_new").val())) {
        error = "Please use four-digit military time. Example: 1430 ";
        error_count++;
        $("#arrival_time_new").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#arrival_time_new").parent().addClass("tableErrorColor");
        $("#arrival_time_new").addClass("formError");
    } else {var checkin_time = verifyMilitaryTime($("#arrival_time_new").val());}
    
    if( !verifyMilitaryTime($("#departure_time_new").val())) {
        error = "Please use four-digit military time. Example: 1430 ";
        error_count++;
        $("#departure_time_new").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#departure_time_new").parent().addClass("tableErrorColor");
        $("#departure_time_new").addClass("formError");
    } else {var checkout_time = verifyMilitaryTime($("#departure_time_new").val());}

    if (checkin_time > checkout_time) {
        error = "Departure time must be after arrival time.";
        error_count++;
        $("#arrival_time_new").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#arrival_time_new").parent().addClass("tableErrorColor");
        $("#arrival_time_new").addClass("formError");
        $("#departure_time_new").parent().append('<span class="errorMessage">'+error+'</span>');
        $("#departure_time_new").parent().addClass("tableErrorColor");
        $("#departure_time_new").addClass("formError");
    }
    var reqFieldList = ['destination_new'];

    jQuery.map(reqFieldList, function(field) { 
    if( !$("#"+field).val()) {
        error = "Please complete required field.";
        error_count++;
        $("#"+field).parent().append('<span class="errorMessage">'+error+'</span>');
        $("#"+field).parent().addClass("tableErrorColor");
        $("#"+field).addClass("formError");
        }
    });

    if(error_count){$("#" + btnAfter).after('<span class="generalErrorMessage" name="message" id="message"><img alt="" src="/tmpo/images/icons/alert.gif"/>Please correct errors above to save destination data.</span>');}
         else {return true;}

}


var driverOption = function(selected, driver) {
    return "<option value='" + driver.id + "' " + 
           (driver.id==selected ? 'selected' : '') + ">" + driver.name + 
           "</option>"
}


var emptyOption = function() {
    return "<option value=''></option>"
}


var actionDrivers = function (selected) {
    options = jQuery.map(drivers, driverOption.partial(selected)).join("")
    return '<select id="driver_id" name="driver_id">' + emptyOption + options + '</select>'
}



function onAddAction() {
    var row1 = [
    '<td><span class="required">*</span> <label for="driver_id">Operator (Last Name, First, M.I.):</label><br>' + actionDrivers() + '</td>',
    '<td><label for="checkin_time">In:</label><br><input type="text" name="checkin_time"id="checkin_time" size="6" value="0000"><br></td>',
    '<td><label for="checkin_miles">Miles:</label><br><input type="text" name="checkin_miles"id="checkin_miles" size="8" value="0"><br></td>',
    '<td><label for="hoursin">Hours:</label><br><input type="text" name="hoursin"id="hoursin" size="5" value="0" /></td>',
    '<td><label for="poc_name">Report to (Last Name, First, M.I.):</label><br><input type="text" name="poc_name"id="poc_name" size="30" value=""><br></td></tr>'
    ];

    var row2 = [
    '<td><label for="operator_sig">Operator\'s signature:</label><br><input type="text" name="operator_sig"id="operator_sig" size="30" /></td>',
    '<td><label for="checkout_time">Out:</label><br><input type="text" name="checkout_time" id="checkout_time" value="0000" size="6" /><br></td>',
    '<td><label for="checkout_miles">Miles:</label><br><input type="text" name="checkout_miles"  id="checkout_miles" size="8" value="0" /><br></td>',
    '<td><label for="hoursout">Hours:</label><br><input type="text" name="hoursout"id="hoursout" size="5" value="0" /></td>',
    '<td><label for="dispatcher_sig">Dispatcher\'s signature:</label><br><input type="text" name="dispatcher_sig" id="dispatcher_sig" size="30" value=""></td>'
    ];

    var buttons = '<td colspan="5">' +
                  '<span id="action_new_save" class="button"><img src="/tmpo/images/icons/save.gif" alt="">Save</span>' + 
                  '<span id="action_new_cancel" class="button"><img src="/tmpo/images/icons/close.gif" alt="">Cancel</span>' + 
                  '</td>'

    var body = '<tbody class="operAdd"><tr>' + 
               row1.join("") +'</tr><tr>' + 
               row2.join("") + '</tr><tr>'+ 
               buttons +'</tr></tbody>'

    which = $("tbody:last", $("#actions").parent().append(body))

    $("#button_add_action").css("visibility", "hidden")
    
    
  $("#action_new_save").click(function(){//validation 
    if( validateAction('action_new_cancel') )
      {
       

      //$("#action_new_save").click(function() {
          var actionDetails = {};
          
              actionDetails.vh_id = attrs_1970.vh_id;
              actionDetails.checkin_miles = $("[name=checkin_miles]", which).val();
              actionDetails.checkout_miles = $("[name=checkout_miles]", which).val();
              actionDetails.checkin_time = $("[name=checkin_time]", which).val();
              actionDetails.checkout_time = $("[name=checkout_time]", which).val();
              actionDetails.poc_name = $("[name=poc_name]", which).val();
              actionDetails.driver_id = $("[name=driver_id]", which).val();

          $.ajax({
              url : '/api/tmpo/vehicles/history/action/',
              type : 'PUT',
              data : actionDetails,
              async : false,
              success : function() {
                  //console.log("action saved")
                  $("tbody", $("#actions").parent()).remove();
                  populateForm();
                  doBinds();
                  
              },
              complete: function() {
              
              $("#button_add_action").css("visibility", "visible")
                //which.remove();
              }
                
          })               

      //});
    
       } 
  });//validation   

    $("#action_new_cancel").click(function() {
        $("#button_add_action").css("visibility", "visible")
        //which.remove();
    });
}

//MARK
function onAddDestination() {
    var row1 = [
        '<td><span class="required">*</span> <label for="toAdd">To:</label><br><input name="destination_new" id="destination_new" value=""></td>',
        '<td><span class="required">*</span> <label for="arrival_time_new">In:</label><br><input name="arrival_time_new" id="arrival_time_new" value=""></td>',
        '<td><span class="required">*</span> <label for="departure_time_new">Out:</label><br><input name="departure_time_new" id="departure_time_new" value=""></td>',
        '<td><label for="releasedAdd">Released by (Signature):</label><br><input name="releasedAdd" size="30"></td>',
        '<td><label for="comments_new">Comments:</label><br><textarea rows="2" cols="35" name="comments_new" id="comments_new"></textarea></td>',
    ];
    var buttons = '<td colspan="5">' + 
                  '<span id="destination_new_save" class="button"><img src="/tmpo/images/icons/save.gif" alt="">Save</span>' + 
                  '<span id="destination_new_cancel" class="button"><img src="/tmpo/images/icons/close.gif" alt="">Cancel</span>' +
                   '</td>';
//which = $("tbody:last", $("#base_from").parent().append(body));
    var body = '<tbody class="destAdd"><tr>' + row1.join("") + '</tr><tr>' + buttons + '</tr></tbody>';
    which = $("tbody:last", $("#base_from").parent().append(body));
    //$("tbody[class='existingDest']:last").after(body);
    $("#button_add_destination").css("visibility", "hidden");

    $("#destination_new_cancel").click(function() {
        $(".destAdd").remove();
        $("#button_add_destination").css("visibility", "visible");
    });
    
    

    $("#destination_new_save").click(function(){ 
    if( validateDest('destination_new_cancel') ) 
     { //validation
      
      
      //$("#destination_new_save").click(function() {
          destDetails = {};
              destDetails.vh_id = attrs_1970.vh_id;
              destDetails.destination = valOf("#destination_new");
              destDetails.arrival_time = valOf("#arrival_time_new");
              destDetails.departure_time = valOf("#departure_time_new");
              destDetails.comments = valOf("#comments_new");

          $.ajax({
              url:destination_url,
              type:'PUT',
              data:destDetails,
              success:function (){
                  $(".destAdd").remove();
                  $("#button_add_destination").css("visibility", "visible");
                  resetForm();
              }
          })
      //});
      
     }
   });//validation

}


var onEditAction = function (r){
$("#button_add_action").css("visibility", "hidden")
    $("tbody").unbind();
    var oper = '<td><span class="required">*</span>' +
               '<label for="driver_id"> Operator (Last Name, First, M.I.):</label>' +
               '<br>' + actionDrivers(r.driver_id) + '</td>';

    var checkin_time = '<td><label for="checkin_time">In:</label><br><input id="checkin_time" value="'+formatTime(r.checkin_time)+'"></td>';
    var checkin_miles = '<td><label for="checkin_miles">Miles:</label><br><input id="checkin_miles" value="'+r.checkin_miles+'"></td>';
    var hoursin = '<td><label for="hoursinEdit">Hours:</label><br><input id="hoursin" type="text" value="0" size="5" name="hoursin"/></td>';
    var report = '<td><label for="poc_name">Report to (Last Name, First, M.I.):</label><br><input id="poc_name" value="'+r.poc_name+'"></td>';
    var opsign ='<td>	<label for="opsignEdit"> Operator\'s signature:</label><br><input name="opsignEdit" type="text" id="opsignEdit" size="30" /></td>';
    var checkout_time = '<td><label for="checkout_time">Out:</label><br><input id="checkout_time" value="'+formatTime(r.checkout_time)+'"></td>';
    var checkout_miles = '<td><label for="checkout_miles">Miles:</label><br><input id="checkout_miles" value="'+r.checkout_miles+'"></td>';
    var hoursout = '<td><label for="hoursoutEdit">Hours:</label><br><input id="hoursout" type="text" value="0" size="5" name="hoursout"/></td>';
    var dispatcher = '<td>	<label for="dispatcherEdit">Dispatcher\'s signature:</label><br><input type="text" id="dispatcherEdit" size="30" /></td>';
    var form_row1 = oper+checkin_time+checkin_miles+hoursin+report;
    var form_row2 = opsign+checkout_time+checkout_miles+hoursout+dispatcher;

    var buttons = '<td colspan="5">' +
                  '<span id="action_edit_save" class="button"><img src="/tmpo/images/icons/save.gif" alt="">Save</span>' +
                  '<span id="action_edit_cancel" class="button"><img src="/tmpo/images/icons/close.gif" alt="">Cancel</span>' +
                  '<span id="action_edit_delete" class="button"><img src="/tmpo/images/icons/delete.gif" alt="">Remove Operator</span></td>';

    $("#action_"+r.vha_id).replaceWith('<tbody style="border:1px solid blue" id="action_edit"><tr>'+form_row1+'</tr><tr>'+form_row2+'</tr><tr>'+buttons+'</tr></tbody>');


    $("#action_edit_cancel").click(resetForm)
    $("#action_edit_save").click(function(){ if (validateAction('action_edit_delete')) {updateAction(r.vha_id)} });//updateAction.partial(r.vha_id)
    $("#action_edit_delete").click(deleteAction.partial(r))
}


var onEditDestination = function(r) {
    $("tbody").unbind();
    var destination = '<td><label for="destination">To:</label><br><input id="destination_new" value="'+r.destination+'"></td>';
    var arrive_time = '<td><label for="destination_arrive">In:</label><br><input id="arrival_time_new" value="'+formatTime(r.arrival_time)+'"></td>';
    var depart_time = '<td><label for="destination_depart">Out:</label><br><input id="departure_time_new" value="'+formatTime(r.departure_time)+'"></td>';
    var released = '<td><label for="releasedEdit">Released by (Signature):</label><br><input id="releasedAdd" size="30" /></td>';
    if (!r.comments){var comments = '<td><label for="destination_comments">Comments:</label><br><textarea rows="2" cols="35" id="comments_new"></textarea></td>';}
      else {var comments = '<td><label for="destination_comments">Comments:</label><br><textarea rows="2" cols="35" id="comments_new">'+r.comments+'</textarea></td>';}
    var form_row1 = destination+arrive_time+depart_time+released+comments;
    var buttons = '<td colspan="5"><span id="destination_save" class="button"><img src="/tmpo/images/icons/save.gif" alt=""> Save</span><span id="destination_cancel" class="button"><img src="/tmpo/images/icons/close.gif" alt=""> Close</span><span id="destination_delete" class="button"><img src="/tmpo/images/icons/delete.gif" alt=""> Delete</span></td>';
    $("#destination_"+r.vhd_id).replaceWith('<tbody id="destination_edit"><tr>'+form_row1+'</tr><tr>'+buttons+'</tr></tbody>');
    $("#destination_cancel").click(function() { $("tbody.destination_edit").remove(); resetForm(); });
    $("#destination_save").click(function(){if(validateDest('destination_delete')) {updateDest(r.vhd_id)} });
    $("#destination_delete").click(function(){deleteDest(r)});
}


var driverName = function(driver_id) {

try{
    var n = $(drivers).filter("[id=" + driver_id + "]")[0].name;
    }
    catch(err){
      var n = '';
    }

    return n;
}

var FuelType = function(type) { 
 $("#fuel option[value='" + type + "']").attr("selected", "selected");
}
var OilType = function(type) { 
 $("#oil option[value='" + type + "']").attr("selected", "selected");
}


var populateForm = function() {
    loadVehicleHistory();
    $("#date").text(display_date);
    if (attrs_1970) {
        $("#vehicle").text(vehicle_no);
        //$("#org").val(attrs_1970.organization_name);
        $("#registration").val(attrs_1970.registration_number);
        $("#admin").val(attrs_1970.administration_number);
        //$("#fuel").val(attrs_1970.fuel);
        FuelType(attrs_1970.fuel);
        //$("#oil").val(attrs_1970.oil);
        OilType(attrs_1970.oil);
        $("#from").val(attrs_1970.departure_location);
        $("#depart").val(formatTime(attrs_1970.departure_time));
        $("#trip").val(attrs_1970.trip);
        $("#passengers").val(attrs_1970.passengers);
        $("#tons_of_cargo").val(attrs_1970.tons_of_cargo);
        $("#standby_status").val(attrs_1970.standby_status);
        $("#totalmiles").val(attrs_1970.standby_status);
    }
    if (actions) {
        for (var i=0; i<actions.length; i++) {
            var vha_id = actions[i].vha_id;
            // row 1
            
            var oper = '<td><span id="editAction'+vha_id+'" class="hoverButton">Edit</span><span class="required">*</span><label for="action_history_s_'+vha_id+'"> Operator (Last Name, First, M.I.):</label><br><span id="action_history_s'+vha_id+'" >'+ driverName(actions[i].driver_id)+'</span></td>';
            var checkin_time = '<td><label for="checkin_time_'+vha_id+'">In:</label><br><span id="checkin_time_'+vha_id+'">'+formatTime(actions[i].checkin_time)+'</span></td>';
            var checkin_miles = '<td><label for="checkin_miles_'+vha_id+'">Miles:</label><br><span id="checkin_miles_'+vha_id+'">'+actions[i].checkin_miles+'</span></td>';
            var hoursin = '<td><label for="hoursin_'+vha_id+'">Hours:</label><br><span id="hoursin_'+vha_id+'"></span></td>';
            var report = '<td><label for="report_'+vha_id+'">Report to (Last Name, First, M.I.):</label><br><span id="report_'+vha_id+'">'+actions[i].poc_name+'</span></td>';
            // row 2
            /*var opsign ='<td rowspan="2"><label for="opsign_'+vha_id+'"> Operator\'s signature:</label><br><input name="opsign_'+vha_id+'" type="text" id="opsign_'+vha_id+'" size="30" /></td>';
            var checkout_time = '<td><label for="checkout_time_'+vha_id+'">Out:</label><br><span id="checkout_time_'+vha_id+'">'+formatTime(actions[i].checkout_time)+'</span></td>';
            var checkout_miles = '<td><label for="checkout_miles_'+vha_id+'">Miles:</label><br><span id="checkout_miles_'+vha_id+'">'+actions[i].checkout_miles+'</span></td>';
            var hoursout = '<td><label for="hoursout_'+vha_id+'">Hours:</label><br><span id="hoursout_'+vha_id+'"></span></td>';
            var dispatcher = '<td rowspan="2">	<label for="dispatcher_'+vha_id+'">Dispatcher\'s signature:</label><br><input type="text" id="dispatcher_'+vha_id+'" size="30" /></td>';
            */
            var opsign ='<td rowspan="2"><label for="opsign_'+vha_id+'"> Operator\'s signature:</label><br></td>';
            var checkout_time = '<td><label for="checkout_time_'+vha_id+'">Out:</label><br><span id="checkout_time_'+vha_id+'">'+formatTime(actions[i].checkout_time)+'</span></td>';
            var checkout_miles = '<td><label for="checkout_miles_'+vha_id+'">Miles:</label><br><span id="checkout_miles_'+vha_id+'">'+actions[i].checkout_miles+'</span></td>';
            var hoursout = '<td><label for="hoursout_'+vha_id+'">Hours:</label><br><span id="hoursout_'+vha_id+'"></span></td>';
            var dispatcher = '<td rowspan="2">	<label for="dispatcher_'+vha_id+'">Dispatcher\'s signature:</label><br></td>';
            // row 3
            var total_time ='<td>	<label for="total_'+vha_id+'"> Total Hours:</label><br><span id="total_'+vha_id+'">'+((actions[i].checkin_time-actions[i].checkout_time)/100)+'</span></td>';
            var total_miles = '<td><label for="miles_'+vha_id+'">Total Miles:</label><br><span id="miles_'+vha_id+'">'+(actions[i].checkin_miles-actions[i].checkout_miles)+'</span></td>';
            var hours_total = '<td><label for="hourstotal_'+vha_id+'">Hours:</label><br><span id="hourstotal_'+vha_id+'">&nbsp;</span></td>';
            // form up the rows
            var form_row1 = oper+checkin_time+checkin_miles+hoursin+report;
            var form_row2 = opsign+checkout_time+checkout_miles+hoursout+dispatcher;
            var form_row3 = total_time+total_miles+hours_total;
            // determine where things get placed 
            if (i > 0) {
                $("#action_"+actions[i-1].vha_id+"").after(
                    '<tbody id="action_' + vha_id +
                    '" class=""><tr>'+form_row1+'</tr><tr>'+form_row2+
                    '</tr><tr>'+form_row3+'</tr></tbody>'); 
            } else {
               $("thead:contains('Action')").after(
                   '<tbody id="action_'+vha_id+'" class="" ><tr>'+form_row1+
                   '</tr><tr>'+form_row2+'</tr><tr>'+form_row3+'</tr></tbody>');
            }
        }
    }
    if (destinations) {
        for (var i=0; i<destinations.length; i++) {
            var k = destinations[i].vhd_id;
            // row 1
            var destination = '<td><span id="editDestination'+k+'" class="hoverButton">Edit</span><label for="to_'+k+'">To:</label><br><span id="to_'+k+'">'+destinations[i].destination+'</span></td>';
            var arrive_time = '<td><label for="arrive_'+k+'">In:</label><br><span id="arrive_'+k+'">'+formatTime(destinations[i].arrival_time)+'</span></td>';
            var depart_time = '<td><label for="depart_'+k+'">Out:</label><br><span id="depart_'+k+'">'+formatTime(destinations[i].departure_time)+'</span></td>';
            var released = '<td><br></td>';//<label for="released">Released by (Signature):</label>
            if (!destinations[i].comments){
              var comments = '<td><label for="comments_'+k+'">Comments:</label><br><span id="comments_'+k+'"></span></td>';
            } else {
              var comments = '<td><label for="comments_'+k+'">Comments:</label><br><span id="comments_'+k+'">'+destinations[i].comments+'</span></td>';
            }
          // form up the rows
            var form_row1 = destination+arrive_time+depart_time+released+comments;
          // determine where things get placed
            if (i > 0) { $("#destination_"+destinations[i-1].vhd_id+"").after('<tbody class="existingDest" id="destination_'+k+'"><tr>'+form_row1+'</tr></tbody>'); }
             else { $("#base_from").after('<tbody class="existingDest" id="destination_'+k+'"><tr>'+form_row1+'</tr></tbody>'); }
            }
     }
}


var doBinds = function() {
    jQuery.map(actions, function(row) {
    
        var actid = row.vha_id;
        var actnode = $("#action_" + actid)
        actnode.unbind();
        actnode.hover(
            function() {actnode.addClass('highlight')},
            function() {actnode.removeClass('highlight')}
        );
        $("#editAction" + actid).unbind().click(onEditAction.partial(row));
        $("#action_" + actid).click(onEditAction.partial(row));
    });
    
    
    jQuery.map(destinations, function(row) {
    
        var destid = row.vhd_id;
        var destnode = $("#destination_" + destid)
        destnode.unbind();
        destnode.hover(
            function() {destnode.addClass('highlight')},
            function() {destnode.removeClass('highlight')}
        );
        $("#editDestination" + destid).unbind().click(onEditDestination.partial(row));
        $("#destination_" + destid).click(onEditDestination.partial(row));
    });
}


var resetForm = function() {
    $("#button_add_action").css("visibility", "visible");
    jQuery.map(actions, function(row) { $("#action_" + row.vha_id).remove() });
    jQuery.map(destinations, function(row){ $("#destination_" + row.vhd_id).remove() });
    $("#action_edit").remove();
    $("#destination_edit").remove();  
    populateForm();
    doBinds();
    $("table.inline tbody").removeClass("tableAlternateColor")
    $("table.inline tbody:odd").addClass("tableAlternateColor")
}


var onCancel = function() {
    // instead of history.back, we reformulate the history page and
    // nav there to load any new data
    window.location.href = '/tmpo/vehicles/history/?id=' + 
                           attrs_1970.vehicle_id + '&date=' + 
                           attrs_1970.dd1970_date.substr(0, 7)
}

function validateRequestForm(btnAfter){

   var error_count = 0;
    $("#message").remove();
    $("td[class='tableErrorColor']").removeClass("tableErrorColor");
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("select[class='formError']").removeClass('formError');

  
    var reqFieldList = ['registration','admin','fuel','oil','org','trip','passengers'];

    jQuery.map(reqFieldList, function(field) { 
    if( !$("#"+field).val()) {
        error = "Please complete required field.";
        error_count++;
        $("#"+field).parent().append('<br/><span class="errorMessage">'+error+'</span>');
        $("#"+field).parent().addClass("tableErrorColor");
        $("#"+field).addClass("formError");
        }
    });

    if(error_count){$("#" + btnAfter).after('<span class="generalErrorMessage" name="message" id="message"><img alt="" src="/tmpo/images/icons/alert.gif"/>Please correct errors above to save destination data.</span>');}
         else {return true;}

}

$(document).ready(function() {
    Functional.install();
    getSiteCfg();
    $("#button_add_action").click(onAddAction);
    $("#button_add_destination").click(onAddDestination);    
    //$("#button_save").click(onSave);
    $("#button_save").click(function(){if( validateRequestForm('button_save') ){onSave();} });
    
    $("#button_cancel").click(onCancel);
    vehicle_id = getQueryStringVariable('id');
    loadDrivers();
    resetForm();
    $("#button_print").click( makePrinter(".mainContent") );
});